package com.runen.infinitemovement.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.ColumnActivity;
import com.runen.infinitemovement.activity.MainActivity;
import com.runen.infinitemovement.activity.WebActivity;
import com.runen.infinitemovement.adapter.NewBannerAdapter;
import com.runen.infinitemovement.adapter.NewsAdapter;
import com.runen.infinitemovement.adapter.NewsHeaderAdapter;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.NewsEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.indicator.RectangleIndicator;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class NewsFragmentV2 extends Fragment {

    @BindView(R.id.srl)
    SmartRefreshLayout srl;
    @BindView(R.id.rcv_content)
    RecyclerView rcv_content;
    @BindView(R.id.rcv_header)
    RecyclerView rcv_header;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.ll_header)
    LinearLayout ll_header;
    @BindView(R.id.tv_null)
    TextView tv_null;

    private int page = 1;
    private int limit = 10;
    private String subjectId;

    private NewsAdapter newsAdapter;
    private NewsHeaderAdapter newsHeaderAdapter;
    private NewsEntity newsEntity;

    public static Fragment getInstance(String subjectId) {
        Fragment fragment = new NewsFragmentV2();
        Bundle bundle = new Bundle();
        bundle.putString(ActivityCompat.SUBJECT_ID, subjectId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_v2, container, false);
        ButterKnife.bind(this, view);
        subjectId = getArguments().getString(ActivityCompat.SUBJECT_ID);
        initView();
        initData();
        return view;
    }

    private void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rcv_content.setLayoutManager(layoutManager);
        newsAdapter = new NewsAdapter(getActivity());
        rcv_content.setAdapter(newsAdapter);

        rcv_content.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (getActivity() != null) {
                        Glide.with(getActivity()).resumeRequests();//恢复Glide加载图片
                    }
                } else {
                    if (getActivity() != null) {
                        Glide.with(getActivity()).pauseRequests();//禁止Glide加载图片
                    }
                }
            }
        });
        newsAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra("LINK_URL",
                        String.format(Constant.H5_CONTANST_DETAIL, UserAPI.getUserToken(), newsAdapter.getData().get(position).informationId));
                startActivity(intent);
            }
        });

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(getActivity());
        layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        rcv_header.setLayoutManager(layoutManager1);
        newsHeaderAdapter = new NewsHeaderAdapter(getActivity());
        rcv_header.setAdapter(newsHeaderAdapter);

        newsHeaderAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent intent = new Intent(getActivity(), ColumnActivity.class);
                intent.putExtra("subjectId", newsHeaderAdapter.getData().get(position).informationId);
                getActivity().startActivity(intent);
            }
        });


        srl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                initData();
                srl.finishRefresh();
            }
        });
        srl.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (newsAdapter.getData().size() >= newsEntity.data.count) {
                    ToastUtils.showShort("已无更多数据");
                    srl.finishLoadMore();
                    return;
                }
                page++;
                initData();
                srl.finishLoadMore();
            }
        });
    }

    private void initData() {
        Map<String, Object> params = new HashMap<>();
        params.put("limit", limit);
        params.put("page", page);
        params.put("subjectId", subjectId);
        new ActivityAPI().informationListBySubjectId(params, new BaseResultCallback<NewsEntity>() {
            @Override
            public void onResponse(NewsEntity response) {
                if (response != null && response.code == 0) {
                    newsEntity = response;
                    if (page == 1) {
                        tv_null.setVisibility(View.GONE);
                        rcv_content.setVisibility(View.VISIBLE);
                    }
                    setView(response.data);
                } else {
                    if (page == 1) {
                        tv_null.setVisibility(View.VISIBLE);
                        rcv_content.setVisibility(View.GONE);
                    }
                }
            }
        });

    }

    private void setView(NewsEntity.DataBean data) {
        //文章
        if (newsAdapter != null) {
            if (page == 1) {
                newsAdapter.setNewInstance(data.inforMationList);
            } else
                newsAdapter.addData(data.inforMationList);
        }
        if (page == 1) {
            if (data.inforMationList != null && data.inforMationList.size() > 0) {
                tv_null.setVisibility(View.GONE);
                rcv_content.setVisibility(View.VISIBLE);
            } else {
                tv_null.setVisibility(View.VISIBLE);
                rcv_content.setVisibility(View.GONE);
            }
        }

        //banner
        if (getActivity() == null || ((MainActivity) getActivity()).isDestroyed()) {
            return;
        }
        if (data.bannerList != null && data.bannerList.size() > 0) {
            banner.setVisibility(View.VISIBLE);
            List<NewsEntity.DataBean.BannerListBean> bannerEntities = data.bannerList;

            banner.addBannerLifecycleObserver(this)//添加生命周期观察者
                    .setAdapter(new NewBannerAdapter(getActivity(), bannerEntities))
                    .setLoopTime(3000)
                    .setIndicator(new RectangleIndicator(getActivity()));
        } else
            banner.setVisibility(View.GONE);

        //头像
        if (data.peopleList != null && data.peopleList.size() > 0) {
            ll_header.setVisibility(View.VISIBLE);
            newsHeaderAdapter.setNewInstance(data.peopleList);
        } else
            ll_header.setVisibility(View.GONE);
    }
}
